﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO;
using Microsoft.Scripting.Hosting;

namespace Ruandao.MiniFace
{
    public class PageResult : ActionResult
    {
        public Template Template { get; set; }
        public Dictionary<string, object> Variables { get; set; }

        public PageResult(MiniFace.Template template)
        {
            this.Template = template;
            this.Variables = new Dictionary<string, object>();
        }

        public PageResult(MiniFace.Template template, Dictionary<string,object> variables)
        {
            this.Template = template;
            this.Variables = variables;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            TextWriter writer = context.HttpContext.Response.Output;
            TemplateContext templateContext = new TemplateContext();
            ScriptScope pythonScope = templateContext.PythonScope;
            var controller = context.Controller;
            var httpContext = context.HttpContext;

            pythonScope.SetVariable("ViewBag", controller.ViewBag);
            pythonScope.SetVariable("ViewData", controller.ViewData);
            pythonScope.SetVariable("DetailsModel", controller.ViewData["DetailsModel"]);
            pythonScope.SetVariable("ListModel", controller.ViewData["ListModel"]);

            pythonScope.SetVariable("HttpContext", httpContext);
            pythonScope.SetVariable("Request", httpContext.Request);
            pythonScope.SetVariable("QueryString", httpContext.Request.QueryString);
            pythonScope.SetVariable("QueryBag", httpContext.Request.QueryString.AsDynamic());
            pythonScope.SetVariable("Server", httpContext.Server);
            pythonScope.SetVariable("Response", httpContext.Response);
            pythonScope.SetVariable("User", httpContext.User);
            pythonScope.SetVariable("Items", httpContext.Items);

            foreach (var v in this.Variables)
            {
                pythonScope.SetVariable(v.Key, v.Value);
            }

            Template.Render(templateContext, writer);
        }

    }
}
